#include "TerrainClump.h"
#include "terrain.h"

TerrainClump::TerrainClump(Terrain* terrain, int index, int x, int z, int w, int h)
{
	m_terrain = terrain;
	m_index = index;
	m_clumpX = x;
	m_clumpZ = z;
	m_width = w;
	m_height = h;
}


TerrainClump::~TerrainClump(void)
{
}


void TerrainClump::generateIndices(int width, int numClumps)
{
	int size = width / numClumps;
	int startZ = size * m_clumpZ;
	int startX = size * m_clumpX;

	if(m_clumpX > 0){
		startX -= 1;
	}
	if(m_clumpZ > 0){
		startZ -= 1;
	}

	int endZ = startZ + m_height - 1;
	int endX = startX + m_width - 1;

	if(m_clumpZ == 7){
		int s =2;
	}
	for (int z = startZ; z < endZ; ++z)
    {
        for (int x = startX; x < endX; ++x)
        {
			int i0 = (z * width) + x;
			int i1 = ((z + 1) * width) + x;
			int i2 = (z * width) + x + 1;
			int i3 = ((z + 1) * width)  + x;
			int i4 = ((z + 1) * width) + x + 1;
			int i5 = (z * width) + x + 1;

            m_indices.push_back(i0);
            m_indices.push_back(i1);
            m_indices.push_back(i2);

            m_indices.push_back(i3);
            m_indices.push_back(i4);
            m_indices.push_back(i5);
        }
    }

    glGenBuffers(1, &m_indexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * m_indices.size(), &m_indices[0], GL_STATIC_DRAW);
}

void TerrainClump::generateBoundingVolume(std::vector<Vertex> verts)
{
	minX = 1000;
	maxX = -1000;
	minY = 1000;
	maxY = -1000;
	minZ = 1000;
	maxZ = -1000;

	Vertex v;
	for(int i=0; i<m_indices.size(); i++){
		v = verts[m_indices[i]];
		if(v.x < minX){
			minX = v.x;
		}
		else if(v.x > maxX){
			maxX = v.x;
		}

		if(v.y < minY){
			minY = v.y;
		}
		else if(v.y > maxY){
			maxY = v.y;
		}

		if(v.z < minZ){
			minZ = v.z;
		}
		else if(v.z > maxZ){
			maxZ = v.z;
		}
	}

	center.x = (minX + maxX) / 2.0f;
	center.y = (minY + maxY) / 2.0f;
	center.z = (minZ + maxZ) / 2.0f;

	float dist = 0.0f;

	for(int i=0; i<m_indices.size(); i++){
		float diffx = center.x - verts[m_indices[i]].x;
		float diffy = center.y - verts[m_indices[i]].y;
		float diffz = center.z - verts[m_indices[i]].z;
		float d = sqrt((diffx * diffx) + (diffy * diffy) + (diffz * diffz));
		if(d > dist){
			dist = d;
		}
	}

	radius = dist + 0.5f;
}

void TerrainClump::render()
{
	m_terrain->render(m_index);
}